"use client"; // 添加这一行，使组件变为 Client Component
import { useEffect, useState } from "react";
import { DndProvider } from "react-dnd"
import { HTML5Backend } from "react-dnd-html5-backend"
import LeftDropable from "./component/LeftDropable";
import DragLayer from "./component/Draggable/DragLayer"
import MIddleDropableView from "./component/MiddleDropable";
import RightDropableView from "./component/RightDropable";
import { Button, Col, Form, Input, Modal, Row } from "antd";
import { addForm, FormDto, getFormDetail, updateForm } from "@/clientApi/flowable/form";
import styles from "./index.module.css";
import { useSelector } from "react-redux";
import { RootState, useAppDispatch } from "@/store/client";
import { useRouter } from "next/navigation";
import { updateApiData } from "@/store/client/modules/reactdndStore";
type MyConponent = {
  id?: number | string
}
const ReactDndDesignView: React.FC<MyConponent> = ({ id }) => {
  const [formData, setFormData] = useState<FormDto>({
    name: null,
    formContent: null,
    remark: null,
  });
  const [form] = Form.useForm();
  const [open, setOpen] = useState(false);
  const router = useRouter();
  const dispatch = useAppDispatch()
  const boxDataStore = useSelector((state: RootState) => state.reactDnd.boxData);
  const boxIndexStore = useSelector((state: RootState) => state.reactDnd.boxIndex);
  useEffect(() => {
    console.log("idDesign", id)
    if (id && id !== 'add') {
      getList()
    }

  }, [id])
  function getList() {
    getFormDetail(Number(id)).then((res: any) => {
      form.setFieldsValue({
        name: res.data?.name,
        remark: res.data?.remark,
      });
      setFormData((prev) => ({
        ...prev,
        id,
        name: res.data?.name,
        remark: res.data?.remark,
        formContent:JSON.stringify({ boxDataStore, boxIndexStore })
      }))
      dispatch(updateApiData(JSON.parse(res.data.formContent)))
    });
  }

  const handleSave = () => {

    if (id == 'add') {
      // 用户点击“确定”按钮后执行的操作
      addForm(formData).then((res: any) => {
        if (res.code == 200) {
          setOpen(false)
          router.back();
        }
      });
    } else {

      updateForm(formData).then((res: any) => {
        if (res.code == 200) {
          setOpen(false)
          router.back();
        }
      });
    }
    // 在这里可以添加删除记录的逻辑





  }
  const handleOpen = () => {
    setOpen(true)


  }
  const onValuesChange = (changedValues: any, allValues: any) => {
    if (id == 'add') {
      setFormData((prevState: any) => ({
        ...allValues,
        formContent: JSON.stringify({ boxDataStore, boxIndexStore })
      }));
    } else {
      setFormData((prevState: any) => ({
        ...allValues,
        id: id,
        formContent: JSON.stringify({ boxDataStore, boxIndexStore })
      }));
    }
  };

  return (
    <>


      <div className={"w-full h-full"}>
        <DndProvider backend={HTML5Backend}>
          <div className={'w-full  h-full flex justify-around'}>
            <div className={"w-1/10 pr-1 "}>
              <LeftDropable />
            </div>
            <div className={"w-7/10 flex flex-col"}>
              <div className={` w-full flex items-center justify-end p-2`}>
                <Button type="primary" onClick={handleOpen} size="small">Save</Button>

              </div>
              <div className={`flex-1 min-h-0`}>  <MIddleDropableView /></div>

            </div>
            <div className={"w-2/10 pl-1"}>
              <RightDropableView />
            </div>
          </div>
          {/* <DragLayer /> */}
        </DndProvider>
      </div>
      {open && <Modal
        forceRender
        open={open}
        title={"新增表单"}
        footer={null}
        onCancel={() => {
          setOpen(false)
        }}
      >
        <Form form={form}
          name="saveform"
          style={{ maxWidth: 500 }}
          onValuesChange={onValuesChange}>
          <Row gutter={2}>
            <Col span={24}>
              <Form.Item
                labelCol={{ span: 4, }}
                label="表单名称"
                name="name"
                rules={[{ required: true, message: "表单名称不能为空", validateTrigger: "blur" }]}
              >
                <Input />
              </Form.Item>
            </Col>
            <Col span={24}>
              <Form.Item
                labelCol={{ span: 4, }}
                label="备注"
                name="remark"
              >
                <Input.TextArea />
              </Form.Item>
            </Col>

            <Col span={24}>
              <Form.Item
                wrapperCol={{ offset: 16, span: 8 }}
              >
                <div className={styles.buttonClass}>
                  <Button type="primary" htmlType="submit" onClick={handleSave}>确认</Button>
                  <Button type="primary" onClick={() => setOpen(false)}>取消</Button>
                </div>
              </Form.Item>
            </Col>
          </Row>
        </Form>
      </Modal>}
    </>
  )

}
export default ReactDndDesignView;